package com.yuanian.ecsplus.bean.entity;

import com.yuanian.ecsplus.bean.CommonModel;
import com.yuanian.ecsplus.enums.QueryMode;
import com.yuanian.ecsplus.exception.EcsPlusException;
import com.yuanian.ecsplus.lambda.SFunction;
import com.yuanian.ecsplus.cache.CacheManager;
import com.yuanian.ecsplus.meta.entity.MetaEntity;
import com.yuanian.ecsplus.model.entity.BaseModel;
import com.yuanian.ecsplus.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Stack;

/**
 * lambada表达式SQL的查询,CRUD
 * @param <T>
 */
public class LambdaModel<T extends BaseModel> {
    //查询条件
    private StringBuilder paramString;

    //查询实体类字节
    private Class<T> clz;

    //and or 操作的栈
    private Stack<String> stack = new Stack<>();

    private boolean sqlStartFlag;

    //当前栈里是否有SQL操作了
    private boolean sqlHaveFlag;

    public LambdaModel(Class<T> clz) {
        this.paramString = new StringBuilder("");
        this.clz = clz;
        QueryMode.setMode(QueryMode.HUMP);
    }

    @NotNull
    private LambdaModel<T> start(String str) {
        if (!stack.isEmpty() && sqlHaveFlag) {
            paramString.append(" " + stack.peek() + " ");
        }
        stack.push(str);
        paramString.append(" ( ");
        sqlStartFlag = true;
        sqlHaveFlag = false;
        return this;
    }

    @NotNull
    private LambdaModel<T> end(String and) {
        if (!stack.isEmpty() && stack.peek().equals(and)) {
            stack.pop();
            paramString.append(" ) ");
        } else {
            throw new EcsPlusException("操作SQL内嵌发生错误");
        }
        sqlStartFlag = false;
        return this;
    }

    public LambdaModel<T> andStart() {
        return start("and");
    }

    public LambdaModel<T> andEnd() {
        return end("and");
    }

    public LambdaModel<T> orStart() {
        return start("or");
    }

    public LambdaModel<T> orEnd() {
        return end("or");
    }

    public LambdaModel<T> in(SFunction<T, ?> func, List<String> list) {
        paramInit();
        try {
            paramString.append(getFieldName(func)).append(" in ('");
        } catch (Exception e) {
            throw new EcsPlusException(e.getCause());
        }
        String join = StringUtils.join(list, "','");
        paramString.append(join);
        paramString.append("')");
        return this;
    }

    public Object convertObject(Object obj) {
        if (obj instanceof String) {
            if (DateUtils.isDate((String)obj)) {
                return DateUtils.strToDate((String)obj);
            }
            return "'" + obj + "'";
        } else if (obj instanceof Date) {
            return DateUtils.strToDate(DateUtils.toStr((Date)obj));
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal)obj).doubleValue();
        } else {
            return obj;
        }
    }

    public LambdaModel<T> like(SFunction<T, ?> func, Object obj) {
        paramInit();
        try {
            paramString.append("").append(getFieldName(func)).append(" like ").append(convertObject(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public LambdaModel<T> eq(SFunction<T, ?> func, Object obj) {
        paramInit();
        try {
            paramString.append("").append(getFieldName(func)).append(" = ").append(convertObject(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public LambdaModel<T> ne(SFunction<T, ?> func, Object obj) {
        paramInit();
        try {
            paramString.append("").append(getFieldName(func)).append(" != ").append(convertObject(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public LambdaModel<T> lt(SFunction<T, ?> func, Object obj) {
        paramInit();
        try {
            paramString.append("").append(getFieldName(func)).append(" < ").append(convertObject(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public LambdaModel<T> le(SFunction<T, ?> func, Object obj) {
        paramInit();
        try {
            paramString.append("").append(getFieldName(func)).append(" <= ").append(convertObject(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public LambdaModel<T> gt(SFunction<T, ?> func, Object obj) {
        paramInit();
        try {
            paramString.append("").append(getFieldName(func)).append(" > ").append(convertObject(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public LambdaModel<T> ge(SFunction<T, ?> func, Object obj) {
        paramInit();
        try {
            paramString.append("").append(getFieldName(func)).append(" >= ").append(convertObject(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    private void paramInit() {
        sqlHaveFlag = true;
        String str = stack.peek();
        if (str != null && !sqlStartFlag) {
            paramString.append(" " + str + " ");
        } else if (str != null && sqlStartFlag) {
            sqlStartFlag = false;
        } else {
            throw new EcsPlusException("操作SQL内嵌发生错误");
        }
    }

    /**
     * 利用反射获取SFunction的字段名
     * @param func
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private String getFieldName(SFunction<T, ?> func) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        // 直接调用writeReplace
        Method writeReplace = null;
        writeReplace = func.getClass().getDeclaredMethod("writeReplace");
        writeReplace.setAccessible(true);
        //反射调用
        Object sl = writeReplace.invoke(func);
        java.lang.invoke.SerializedLambda serializedLambda = (java.lang.invoke.SerializedLambda) sl;
        String methodName = serializedLambda.getImplMethodName().replace("get", "");
        String fieldName =  methodName.substring(0,1).toLowerCase() + methodName.substring(1);
        return fieldName;
    }

    /**
     * 获取查询条件
     * @return
     */
    public String getSql() {
        return paramString.toString();
    }

    public T selectOne() {
        CommonModel<T> commonModel = new CommonModel(this.clz);
        return commonModel.selectOne(getSql());

    }

    public List<T> selectList() {
        CommonModel<T> commonModel = new CommonModel(this.clz);
        return commonModel.selectList(getSql());
    }

    /**
     * 查询出来后修改
     * @param listHandler
     * @return
     */
    public int batchUpdate(ListHandler<T> listHandler) {
        MetaEntity<T> metaEntity = CacheManager.getInstance().getMetaEntity(clz);
        List<T> list = metaEntity.findList(getSql());
        //设置相关属性
        listHandler.handle(list);
        metaEntity.batchSave(list);
       /* for (T t : list) {
            metaEntity.update(t);
        }*/
        return list.size();
    }

    /**
     * 查询出来后提交
     * @return
     */
    public int batchIssue() {
        MetaEntity<T> metaEntity = CacheManager.getInstance().getMetaEntity(clz);
        List<T> list = metaEntity.findList(getSql());
        for (T t : list) {
            metaEntity.issue(t);
        }
        return list.size();
    }

    /**
     * 查询出来后删除
     * @return
     */
    public int batchDelete() {
        MetaEntity<T> metaEntity = CacheManager.getInstance().getMetaEntity(clz);
        List<T> list = metaEntity.findList(getSql());
        for (T t : list) {
            metaEntity.delete(t);
        }
        return list.size();
    }

    /**
     * 查询出来后,如果查到就修改，没有就插入
     * @param obj
     * @param singleHandler
     * @return
     */
    public int save(T obj, SingleHandler<T> singleHandler) {
        MetaEntity<T> metaEntity = CacheManager.getInstance().getMetaEntity(clz);
        T t = selectOne();
        if (t != null) {
            singleHandler.handle(t);
            metaEntity.update(t);
        } else {
            metaEntity.insert(obj);
        }
        return 1;
    }

    public interface ListHandler<T> {
        void handle(List<T> list);
    }

    public interface SingleHandler<T> {
        void handle(T list);
    }

}
